package com.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.util.CookieUtil;
import com.util.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
        String uri = request.getRequestURI();
        uri = uri.toLowerCase();
//        System.out.println("当前路径为:" + uri);
//            Userinfo user = (Userinfo) request.getSession().getAttribute("user");
        String token = CookieUtil.readCookieToken(request);
        String userKey = DigestUtils.md5Hex(token);
        String userRedis = redisUtil.get(userKey);
        if (token == null || "".equals(token) || "TOKEN_SHARE".equals(token) || null == userRedis) {
            System.out.println("已经被拦截路径为:" + uri);
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            out.write("<script>alert('请先登录');location.href='login'</script>");
            return false;
        }
        HttpSession session = request.getSession();
        JSONObject jsonInfo = JSONObject.parseObject(userRedis);
        String loginName = (String) jsonInfo.get("loginName");
        System.out.println(loginName);
        session.setAttribute("loginName", loginName);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
//        System.out.println("afterCompletion---");
    }
}
